﻿
Imports System.IO
Imports std

Public Class iplist
    'use char, so can list a subdomain
    Private t As trie(Of Char, Boolean, _maxUInt16, _char_to_uint32) = Nothing
    Private WithEvents monitor As saferFileSystemWatcher = Nothing

    Public Sub insert(ByVal ip As String)
        kickLeftRightBlank(ip)
        If Not isemptystring(ip) Then
            t.insert(ip.ToCharArray(), True)
        End If
    End Sub

    Public Sub initial(ByVal listfile As String)
        monitor = New saferFileSystemWatcher()
        monitor.File = listfile
        monitor.EnableRaisingEvents = True
        monitor_changes()
    End Sub

    Public Function inlist(ByVal ip As String) As Boolean
        Return t.findfront(ip.ToCharArray()) <> t.end()
    End Function

    Public Sub New()
        t = New trie(Of Char, Boolean, _maxUInt16, _char_to_uint32)()
    End Sub

    Public Sub New(ByVal listfile As String)
        Me.new()
        initial(listfile)
    End Sub

    Private Sub monitor_changes() Handles monitor.changes
        raiseError("caught iplist file updated, " + monitor.file + ", reload...")
        t.clear()
        Dim s As String = Nothing
        If Not readfile(monitor.file, s) Then
            raiseError("cannot read listfile " + monitor.file + ", ignore.", errorHandle.errorType.warning)
        Else
            Dim words As vector(Of String) = Nothing
            strsepar(s, character.newline + character.tab + character.blank + character.comma, words, True)
            If Not words Is Nothing AndAlso words.size() > 0 Then
                Dim i As Int64
                For i = 0 To words.size() - 1
                    insert(words(i))
                Next
            End If
        End If
    End Sub
End Class
